package com.gwd.task.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.gwd.task.entity.GroupEntity;
import com.gwd.task.exception.DataException;
import com.gwd.task.model.GroupDTO;
import com.gwd.task.model.PageUtils;
import com.gwd.task.model.UserDTO;
import com.gwd.task.model.transfer.GroupInterface;
import com.gwd.task.repository.GroupRepository;
import com.gwd.task.services.GroupServer;
import com.gwd.task.services.UserGroupServer;
import com.gwd.task.services.UserServer;
import com.gwd.task.untils.ListPredicate;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/11/11 10:04
 */
@Service
public class GroupServerImpl implements GroupServer {

    @Resource
    private GroupRepository groupRepository;
    @Resource
    private UserServer userServer;
    @Resource
    private UserGroupServer userGroupServer;

    @Override
    public List<GroupDTO> findAll(Long userId) {
        UserDTO user = userServer.findById(userId);
        List<GroupDTO> groupDTOList = groupRepository.findByActive().stream().map(GroupDTO::new).collect(Collectors.toList());
        if (user.getRole().equals("admin")||user.getRole().equals("leader")) {
            return groupDTOList;
        }
        List<Long> idList = userGroupServer.findGroupIdListByUserId(userId);
        if (idList.size()==0) {
            return new ArrayList<>();
        }

        return groupDTOList.stream().filter(e -> idList.contains(e.getGroupId())).collect(Collectors.toList());
    }

    @Override
    public List<GroupDTO> findAll() {
        return groupRepository.findAll().stream().map(GroupDTO::new).collect(Collectors.toList());
    }

    @Override
    public PageUtils findByPage(GroupDTO dto, PageUtils pageUtils) {
        Page<GroupEntity> all = groupRepository.findAll((Specification<GroupEntity>) (root, query, cb) ->
                        ListPredicate.of(root, query, cb)
                                .like("groupName", dto.getGroupName())
                                .equal("groupId", dto.getGroupId())
                                .equal("groupLeader", dto.getGroupLeader())
                                .equal("remove", dto.getRemove())
                                .finish().getRestriction(),
                        pageUtils.convert());

        pageUtils.convert(all);

        List<GroupDTO> groupDTOList1 = all.get().map(GroupDTO::new).collect(Collectors.toList());
        List<GroupInterface> groupDTOList2 = groupRepository.findByGroupList();
        List<UserDTO> userDTOList = userServer.findAll();
        groupDTOList1.forEach(d1 -> {
            groupDTOList2.forEach(d2 -> {
                if (d1.getGroupId().equals(d2.getGroupId())) {
                    d1.setMembers(d2.getMembers());
                }
            });
            userDTOList.forEach(u -> {
                if (d1.getGroupLeader().equals(u.getUserId())) {
                    d1.setLeaderName(u.getUserName());
                }
            });
        });

        pageUtils.setContent(groupDTOList1);

        return pageUtils;
    }

    @Override
    public void save(GroupDTO dto) {
        GroupEntity save;
        if (dto.getGroupId()!=null) {
            Optional<GroupEntity> entity = groupRepository.findById(dto.getGroupId());
            if (!entity.isPresent()) {
                throw new DataException("DtoId:" + dto.getGroupId() + "对应数据不存在。");
            }
            save = entity.get();
        } else {
            save = new GroupEntity();
        }
        BeanUtil.copyProperties(dto, save, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        save.setMembers(dto.getMembersList().toString()
                .replaceAll("\\[","")
                .replaceAll("]","")
                .replaceAll(" ",""));
        GroupEntity e = groupRepository.save(save);

        userGroupServer.save(e.getGroupId(), dto.getMembersList());
    }

    @Override
    public void remove(Long id) {
        groupRepository.findById(id).ifPresent(entity -> {
            entity.setRemove(1);
            groupRepository.save(entity);
        });
    }

    @Override
    public void active(Long id) {
        groupRepository.findById(id).ifPresent(entity -> {
            entity.setRemove(0);
            groupRepository.save(entity);
        });
    }
}
